<template>
  <div class="cart">
    <div class="list">
      <!-- 列表顶部盒子 -->
      <div class="list-top-box">
        <div class="list-top">
          <a href="#">
            <span></span>
            <p>返回</p>
          </a>
          <h2>商品列表</h2>
        </div>
        <div class="list-inputnavbox">
          <div class="list-input">
            <input type="text" placeholder="     🔍  请输入搜索关键字">
          </div>
          <div class="list-navbox">
            <ul>
              <li>综合排序</li>
              <li>销量</li>
              <li class="pai" @click="sortPrice">价格<span ref="priceSpan">⬆</span></li>
              <li>好评度</li>
              <li>店铺</li>
              <li>筛选</li>
            </ul>
          </div>
        </div>
      </div>

      <div class="list-center">
        <!-- 下拉刷新提示 -->
        <div class="pull-refresh" :style="{ height: refreshHeight + 'px' }">
          <p>{{ refreshText }}</p>
        </div>

        <!-- 滚动内容区 -->
        <div class="box-center-top" @touchstart="handleTouchStart($event)" @touchmove="handleTouchMove($event)"
          @touchend="handleTouchEnd($event)" ref="scrollContainer">
          <div class="center-box" v-for="item in goodslist" :key="item.id" @click="getGoodsDesc(item.id)">
            <div class="center-left">
              <img :src="'http://43.138.15.137:4000/' + item.img" alt="">
            </div>
            <div class="center-right">
              <h3>{{ item.goodsname }}</h3>
              <h4>{{ item.description || '描述信息' }}</h4>
              <p>￥{{ item.price }}</p>
            </div>
          </div>

          <!-- 加载更多提示 -->
          <div v-if="isLoadingMore" class="loading-more">
            <span>加载中...</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getGoodsListAPI } from '@/api/goods/goodslist'
export default {
  name: 'Goodlist',
  data() {
    return {
      goodslistform: {
        cateid: this.$route.query.cateid,
        type: this.$route.query.type,
        page: 1,
        size: 6
      },
      goodslist: [],
      // 触摸相关变量
      touchStartY: 0,
      touchMoveY: 0,
      isDragging: false,
      // 刷新相关变量
      refreshText: '下拉可刷新',
      refreshHeight: 0,
      maxRefreshHeight: 60, // 最大下拉高度
      // 加载更多相关变量
      isLoadingMore: false,
      hasMoreData: true
    }
  },
  mounted() {
    this.getGoodsList()
  },
  methods: {
    async getGoodsList() {
      try {
        const res = await getGoodsListAPI('getgoodlist', {
          ...this.goodslistform
        });

        if (res && res.list && res.list.goodData) {
          // 第一页数据直接替换，后续页数据追加
          if (this.goodslistform.page === 1) {
            this.goodslist = res.list.goodData;
          } else {
            this.goodslist = [...this.goodslist, ...res.list.goodData];
          }

          // 判断是否还有更多数据
          this.hasMoreData = res.list.goodData.length >= this.goodslistform.size;
        } else {
          console.error('获取商品列表数据格式错误:', res);
        }
      } catch (error) {
        console.error('获取商品列表失败:', error);
      } finally {
        // 重置加载状态
        this.isLoadingMore = false;
      }
    },

    sortPrice() {
      if (!this.$refs.priceSpan) return;

      if (this.$refs.priceSpan.style.transform === 'rotate(180deg)') {
        this.goodslist.sort((a, b) => b.price - a.price);
        this.$refs.priceSpan.style.transform = 'rotate(0deg)';
      } else {
        this.goodslist.sort((a, b) => a.price - b.price);
        this.$refs.priceSpan.style.transform = 'rotate(180deg)';
      }
    },

    handleTouchStart(e) {
      // 记录触摸起始位置
      this.touchStartY = e.touches[0].clientY;
      this.isDragging = true;
      this.refreshHeight = 0;
    },

    handleTouchMove(e) {
      if (!this.isDragging || this.isLoadingMore) return;

      const container = this.$refs.scrollContainer;
      if (!container) return;

      this.touchMoveY = e.touches[0].clientY;
      const deltaY = this.touchMoveY - this.touchStartY;

      // 处理下拉刷新（只有在滚动到顶部时才允许下拉）
      if (deltaY > 0 && container.scrollTop <= 0) {
        // 阻止页面默认滚动
        e.preventDefault();

        // 限制最大下拉高度
        this.refreshHeight = Math.min(deltaY / 2, this.maxRefreshHeight);

        // 更新刷新提示文本
        if (this.refreshHeight >= this.maxRefreshHeight) {
          this.refreshText = '松开立即刷新';
        } else {
          this.refreshText = '下拉可刷新';
        }
      }
    },

    async handleTouchEnd() {
      if (!this.isDragging) return;

      const container = this.$refs.scrollContainer;
      if (!container) return;

      // 处理下拉刷新
      if (this.refreshHeight >= this.maxRefreshHeight) {
        this.refreshText = '正在刷新...';
        // 重置页码，重新获取第一页数据
        this.goodslistform.page = 1;
        await this.getGoodsList();
        this.refreshText = '刷新完成';
      }

      // 重置刷新状态
      setTimeout(() => {
        this.refreshHeight = 0;
        this.refreshText = '下拉可刷新';
      }, 500);

      // 处理上拉加载更多
      const scrollTop = container.scrollTop;
      const scrollHeight = container.scrollHeight;
      const clientHeight = container.clientHeight;

      // 当滚动到距离底部100px以内，且还有更多数据时加载
      if (scrollTop + clientHeight >= scrollHeight - 100 &&
        this.hasMoreData &&
        !this.isLoadingMore) {
        this.isLoadingMore = true;
        this.goodslistform.page++;
        await this.getGoodsList();
      }

      this.isDragging = false;
    },

    getGoodsDesc(id) {
      console.log('跳转到商品详情页，商品ID:', id);
      // 实际跳转逻辑
      // this.$router.push(`/goodsdetail/${id}`);
    }
  }
}
</script>

<style scoped lang="scss">
// 定义颜色变量
$primary-color: #FF6040;
$primary-light-color: #FF8A80;
$white-color: #fff;
$bg-color: #fafafa;
$text-color: #323233;
$gray-color: #999;

.cart {
  height: 100%;
  width: 10rem;
  overflow: hidden;
  padding-top: 2.4rem;
  background-color: #f5f5f5;
}

.list-top {
  width: 10rem;
  height: 1.0667rem;
  background-color: $primary-color;
  display: flex;
  align-items: center;
  position: relative;
  justify-content: center;
}

.list-top span {
  display: inline-block;
  width: 0.2rem;
  height: 0.2rem;
  border-top: 1px solid $white-color;
  border-right: 1px solid $white-color;
  transform: rotate(225deg);
  margin: 0 0.4rem;
  position: absolute;
  left: 0.4rem;
  top: 0.4533rem;
}

.list-top p {
  font-size: 0.4267rem;
  color: $white-color;
  position: absolute;
  left: 1.0667rem;
  top: 0.2533rem;
}

.list-top h2 {
  font-size: 0.48rem;
  color: $white-color;
  margin: 0 0.4rem;
  font-weight: 400;
}

.list-inputnavbox {
  width: 10rem;
  height: 2.4rem;
  background: linear-gradient($primary-color, $primary-light-color);
}

.list-inputnavbox .list-input {
  width: 10rem;
  height: 1.44rem;
  display: flex;
  justify-content: center;
  align-items: center;
}

.list-inputnavbox .list-input input {
  width: 9.36rem;
  height: 0.9067rem;
  border: none;
  outline: none;
  border-radius: 0.6667rem;
  padding-left: 0.5333rem;
  font-size: 0.3733rem;
}

.list-inputnavbox .list-navbox {
  width: 10rem;
  height: 1.0667rem;
}

.list-inputnavbox .list-navbox ul {
  width: 10rem;
  height: 1.0667rem;
  list-style: none;
  display: flex;
  justify-content: space-around;
  align-items: center;
  color: $white-color;
  padding: 0 0.2667rem;
  margin: 0;
}

.list-inputnavbox .list-navbox ul li {
  cursor: pointer;
  font-size: 0.4267rem;
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.list-inputnavbox .list-navbox ul li span {
  font-size: 0.32rem;
  transition: all 0.3s;
  margin-left: 0.1333rem;
}

.list-center {
  width: 10rem;

  .pull-refresh {
    display: flex;
    justify-content: center;
    align-items: center;
    transition: height 0.3s;
    color: $gray-color;
    font-size: 0.3733rem;
  }

  .center-top {
    width: 10rem;
    height: 1.0667rem;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 0.4267rem;
    font-size: 0.4267rem;
  }
}

.box-center-top {
  width: 10rem;

  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  max-height: calc(100vh - 5.9333rem);
}

.box-center-top .center-box {
  width: 9.1733rem;
  height: 2.3467rem;
  padding: 0.2133rem 0.4267rem;
  background-color: $white-color;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0.2667rem;
  border-radius: 0.1333rem;
}

.box-center-top .center-box .center-left {
  width: 2.3467rem;
  height: 2.3467rem;
  border-radius: 0.1333rem;
  overflow: hidden;
}

.box-center-top .center-box .center-left img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.box-center-top .center-box .center-right {
  width: 6.5867rem;
  height: 2.3467rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-start;
  color: $text-color;
  padding-left: 0.2667rem;
}

.box-center-top .center-box .center-right h3 {
  font-size: 0.3733rem;
  font-weight: 500;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.box-center-top .center-box .center-right h4 {
  font-weight: 400;
  font-size: 0.32rem;
  color: $gray-color;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.box-center-top .center-box .center-right p {
  font-weight: 500;
  font-size: 0.4267rem;
  color: $primary-color;
  margin: 0;
}

.loading-more {
  width: 100%;
  height: 1.0667rem;
  display: flex;
  justify-content: center;
  align-items: center;
  color: $gray-color;
  font-size: 0.3733rem;
}

.list-top-box {
  width: 10rem;
  height: 3.4667rem;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10;
}
</style>
